<?php

class AdminUserController extends BaseController {
    
    public function showLogin() {
        if (Auth::check()) {
            return Redirect::route('adminEscritorio');
        }
        else {
            // show the form
            return View::make('login.index');
        }
    }

    public function doLogin() {
        // validate the info, create rules for the inputs
        $rules = array(
            'user' => 'required',
            'password' => 'required' // password can only be alphanumeric and has to be greater than 3 characters
        );

        // run the validation rules on the inputs from the form
        $validator = Validator::make(Input::all(), $rules);

        // if the validator fails, redirect back to the form
        if ($validator->fails()) {
            return Redirect::to('login')
                            ->withErrors($validator) // send back all errors to the login form
                            ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
        } else {

            // create our user data for the authentication
            $userdata = array(
                'user' => Input::get('user'),
                'password' => Input::get('password')
            );

            // attempt to do the login
            if (Auth::attempt($userdata)) {

                // validation successful!
                // redirect them to the secure section or whatever
                $user = Auth::user()->user;
                return Redirect::to('admin/escritorio')->with('message', "Hola $user!");
                // for now we'll just echo success (even though echoing in a controller is bad)
                // echo 'SUCCESS!';
            } else {

                // validation not successful, send back to form	
                return Redirect::to('login')->with('message', 'User/Password incorecto/s');
            }
        }
    }
    
    public function doLogout() {
        Auth::logout(); // log the user out of our application
        return Redirect::to('login'); // redirect the user to the login screen
    }

}